import * as XLSX from 'xlsx';  // 使用 * as XLSX 以兼容原代码

export class PlantSurveyPoint {
  constructor() {
    this.xh = null;
    this.chineseName = null;
    this.scientificName = null;
    this.distributionAbundanceDescription = null;
    this.longitude = null;
    this.latitude = null;
    this.elevation = null;
    this.slopeDegree = null;
    this.slopePosition = null;
    this.slopeDirection = null;
    this.habitatType = null;
    this.surveyDate = null;
    this.discoveryTime = null;
    this.habitatDisturbance = null;
    this.protectionLevel = null;
    this.discoveryAddress = null;
    this.leagueCity = null;
    this.bannerCountyDistrict = null;
    this.dataSource = null;
    this.observer = null;
    this.plantPhotoId = null;
    this.habitatPhotoId = null;
    this.speciesCharacteristicsDescription = null;
  }
}
export class AnimalSurveyPoint {
  constructor() {
    this.xh = null;
    this.wzm = null;
    this.ldm = null;
    this.shitishuliang = null;
    this.henjishuliang = null;
    this.jd = null;
    this.wd = null;
    this.hb = null;
    this.podu = null;
    this.powei = null;
    this.poxiang = null;
    this.qixi = null;
    this.diaochariqi = null;
    this.discoveryTime = null;
    this.qixiganrao = null;
    this.protectlevel = null;
    this.location = null;
    this.mengshi = null;
    this.qixian = null;
    this.source = null;
    this.guance = null;
    this.zpbh = null;
    this.sjzpbh = null;
    this.tezhengmiaoshu = null;
this.fenbuduodumiaoshu = null;
    this.category = null;
  }
}
export class PlantBasicInfo {
  constructor() {
    this.chineseName = null;
    this.scientificName = null;
    this.familyChinese = null;
    this.familyLatin = null;
    this.genusChinese = null;
    this.genusLatin = null;
    this.photoId = null;
    this.lifeForm1 = null;
    this.lifeForm2 = null;
    this.moistureType = null;
    this.floristicComponent = null;
    this.isExotic = null;
    this.exoticHarmLevel = null;
    this.isChinaEndemic = null;
    this.isRegionEndemic = null;
    this.isNationalProtected = null;
    this.isRegionalProtected = null;
    this.endangeredLevel = null;
    this.threatReasons = null;
    this.distributionInProtected = null;
    this.statusInCommunity = null;
    this.habitatFeatures = null;
    this.mainValue = null;
    this.protectionStatus = null;
    this.speciesDescription = null;
    this.specimenId = null;
  }
}
export class AnimalBasicInfo {
  constructor() {
    this.chineseName = null;
    this.scientificName = null;
    this.familyChinese = null;
    this.familyLatin = null;
    this.genusChinese = null;
    this.genusLatin = null;
    this.photoId = null;
    this.speciesFeatureDesc = null;
    this.habitatDesc = null;
    this.protectionLevel = null;
    this.utilValue = null;
    this.habitatPhotoId = null;
  }
}

export function readPlantSurveyPoints(file) {
  return new Promise((resolve, reject) => {
    if (!file) {
      reject(new Error('No file provided'));
      return;
    }

    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const data = e.target.result;
        const workbook = XLSX.read(data, { type: 'array' });  // 或 { type: 'array' } 如果使用 readAsArrayBuffer
        const sheet = workbook.Sheets['植物调查样点'];
        const points = [];
        if (!sheet) {
          resolve(points);
          return;
        }

        const range = XLSX.utils.decode_range(sheet['!ref']);
        for (let rowNum = range.s.r + 1; rowNum <= range.e.r; rowNum++) {
          const point = new PlantSurveyPoint();
          point.xh = getInteger(sheet, rowNum, 0);
          point.chineseName = getString(sheet, rowNum, 1);
          if(point.chineseName==null||point.chineseName==""){
            continue;
          }
          point.scientificName = getString(sheet, rowNum, 2);
          point.distributionAbundanceDescription = getString(sheet, rowNum, 3);
          point.longitude = getNumber(sheet, rowNum, 4);
          point.latitude = getNumber(sheet, rowNum, 5);
          point.elevation = getNumber(sheet, rowNum, 6);
          point.slopeDegree = getInteger(sheet, rowNum, 7);
          point.slopePosition = getString(sheet, rowNum, 8);
          point.slopeDirection = getString(sheet, rowNum, 9);
          point.habitatType = getString(sheet, rowNum, 10);
          point.surveyDate = getDate(sheet, rowNum, 11);
          point.discoveryTime = getString(sheet, rowNum, 12);
          point.habitatDisturbance = getString(sheet, rowNum, 13);
          point.protectionLevel = getString(sheet, rowNum, 14);
          point.discoveryAddress = getString(sheet, rowNum, 15);
          point.leagueCity = getString(sheet, rowNum, 16);
          point.bannerCountyDistrict = getString(sheet, rowNum, 17);
          point.dataSource = getString(sheet, rowNum, 18);
          point.observer = getString(sheet, rowNum, 19);
          point.plantPhotoId = getString(sheet, rowNum, 20);
          point.habitatPhotoId = getString(sheet, rowNum, 21);
          point.speciesCharacteristicsDescription = getString(sheet, rowNum, 22);

          points.push(point);
        }
        resolve(points);
      } catch (error) {
        reject(error);
      }
    };
    reader.onerror = (error) => reject(error);
    reader.readAsArrayBuffer(file);  // 或者 readAsArrayBuffer(file) 并调整 type 为 'array'
  });
}
export function readAnimalSurveyPoints(file){
    return new Promise((resolve, reject) => {
    if (!file) {
      reject(new Error('No file provided'));
      return;
    }

    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const data = e.target.result;
        const workbook = XLSX.read(data, { type: 'array' });  // 或 { type: 'array' } 如果使用 readAsArrayBuffer
       const sheetNames = [
          '哺乳动物调查样点',
          '鸟类调查样点',
          '鱼类调查样点',
          '节肢动物调查样点'
          // 如果有更多表，可以在这里添加，如 '两栖爬行动物基本信息' 等
        ];
        const allData = {};

        sheetNames.forEach((sheetName) => {
          const sheet = workbook.Sheets[sheetName];
          const points = [];
          if (!sheet) {
            allData[sheetName] = points; // 如果Sheet不存在，返回空数组
            return;
          }
          const range = XLSX.utils.decode_range(sheet['!ref']);
          for (let rowNum = range.s.r + 1; rowNum <= range.e.r; rowNum++) {
            const point = new AnimalSurveyPoint();
            point.xh = getString(sheet, rowNum, 0);
            point.wzm = getString(sheet, rowNum, 1);
            if (point.wzm == null || point.wzm === "") {
              continue; // 跳过中文名为空的行
            }
            point.ldm = getString(sheet, rowNum, 2);
            point.shitishuliang = getNumber(sheet, rowNum, 3);
            point.henjishuliang = getNumber(sheet, rowNum, 4);
            point.jd = getNumber(sheet, rowNum, 5);
            point.wd = getNumber(sheet, rowNum, 6);
            point.hb = getString(sheet, rowNum, 7);
            point.podu = getString(sheet, rowNum, 8);
            point.powei = getString(sheet, rowNum, 9);

            point.poxiang = getString(sheet, rowNum, 10);
            point.qixi = getString(sheet, rowNum, 11);
            point.diaochariqi = getDate(sheet, rowNum, 12);
            point.discoveryTime=getString(sheet, rowNum, 13);
            point.qixiganrao = getString(sheet, rowNum, 14);
            point.protectlevel = getString(sheet, rowNum, 15);

            point.location = getString(sheet, rowNum, 16);
            point.mengshi = getString(sheet, rowNum, 17);
            point.qixian = getString(sheet, rowNum, 18);
            point.source = getString(sheet, rowNum, 19);
            point.guance = getString(sheet, rowNum, 20);

            point.zpbh = getString(sheet, rowNum, 21);
            point.sjzpbh = getString(sheet, rowNum, 22);
            point.tezhengmiaoshu = getString(sheet, rowNum, 23);
            point.fenbuduodumiaoshu = getString(sheet, rowNum, 24);
            var cate="01";
            if(sheetName=="哺乳动物调查样点"){
              cate="01";
            }
            if(sheetName=="鸟类调查样点"){
              cate="02";
            }
            if(sheetName=="鱼类调查样点"){
              cate="03";
            }
            if(sheetName=="节肢动物调查样点"){
              cate="04";
            }
            point.category =cate ;
            points.push(point);
          }
          allData[sheetName] = points;
        });
        resolve(allData); // 返回对象，键为Sheet名，值为对应数组
      } catch (error) {
        reject(error);
      }
    };
    reader.onerror = (error) => reject(error);
    reader.readAsArrayBuffer(file);  // 或者 readAsArrayBuffer(file) 并调整 type 为 'array'
  });
}
export function readPlantBasicInfo(file){
    return new Promise((resolve, reject) => {
    if (!file) {
      reject(new Error('No file provided'));
      return;
    }

    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const data = e.target.result;
        const workbook = XLSX.read(data, { type: 'array' });  // 或 { type: 'array' } 如果使用 readAsArrayBuffer
        const sheet = workbook.Sheets['植物基本信息'];
        const points = [];
        if (!sheet) {
          resolve(points);
          return;
        }

        const range = XLSX.utils.decode_range(sheet['!ref']);
        for (let rowNum = range.s.r + 1; rowNum <= range.e.r; rowNum++) {
          const point = new PlantBasicInfo();
          point.chineseName = getString(sheet, rowNum, 0);
          if(point.chineseName==null||point.chineseName==""){
            continue;
          }
          point.scientificName = getString(sheet, rowNum, 1);
          point.familyChinese = getString(sheet, rowNum, 2);
          point.familyLatin = getString(sheet, rowNum, 3);
          point.genusChinese = getString(sheet, rowNum, 4);
          point.genusLatin = getString(sheet, rowNum, 5);
          point.lifeForm1 = getString(sheet, rowNum, 6);
          point.lifeForm2 = getString(sheet, rowNum, 7);
          point.moistureType = getString(sheet, rowNum, 8);

          point.floristicComponent = getString(sheet, rowNum, 9);
          point.isExotic = getString(sheet, rowNum, 10);
          point.exoticHarmLevel = getString(sheet, rowNum, 11);
          point.isChinaEndemic = getString(sheet, rowNum, 12);
          point.isRegionEndemic = getString(sheet, rowNum, 13);
          point.isNationalProtected = getString(sheet, rowNum, 14);
          point.isRegionalProtected = getString(sheet, rowNum, 15);
          point.endangeredLevel = getString(sheet, rowNum, 16);
          point.threatReasons = getString(sheet, rowNum, 17);

          point.distributionInProtected = getString(sheet, rowNum, 18);
          point.statusInCommunity = getString(sheet, rowNum, 19);
          point.habitatFeatures = getString(sheet, rowNum, 20);
          point.mainValue = getString(sheet, rowNum, 21);
          point.protectionStatus = getString(sheet, rowNum, 22);
          point.speciesDescription = getString(sheet, rowNum, 23);
          point.photoId = getString(sheet, rowNum, 24);
          point.specimenId = getString(sheet, rowNum, 25);
          points.push(point);
        }
        resolve(points);
      } catch (error) {
        reject(error);
      }
    };
    reader.onerror = (error) => reject(error);
    reader.readAsArrayBuffer(file);  // 或者 readAsArrayBuffer(file) 并调整 type 为 'array'
  });
}
export function readAnimalBasicInfo(file){
    return new Promise((resolve, reject) => {
    if (!file) {
      reject(new Error('No file provided'));
      return;
    }

    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const data = e.target.result;
        const workbook = XLSX.read(data, { type: 'array' });  // 或 { type: 'array' } 如果使用 readAsArrayBuffer
       const sheetNames = [
          '哺乳动物基本信息',
          '鸟类基本信息',
          '鱼类基本信息',
          '节肢动物基本信息'
          // 如果有更多表，可以在这里添加，如 '两栖爬行动物基本信息' 等
        ];
        const allData = {};

        sheetNames.forEach((sheetName) => {
          const sheet = workbook.Sheets[sheetName];
          const points = [];
          if (!sheet) {
            allData[sheetName] = points; // 如果Sheet不存在，返回空数组
            return;
          }

          const range = XLSX.utils.decode_range(sheet['!ref']);
          for (let rowNum = range.s.r + 1; rowNum <= range.e.r; rowNum++) {
            const point = new AnimalBasicInfo();
            point.chineseName = getString(sheet, rowNum, 1);
            if (point.chineseName == null || point.chineseName === "") {
              continue; // 跳过中文名为空的行
            }
            point.scientificName = getString(sheet, rowNum, 2);
            point.familyChinese = getString(sheet, rowNum, 3);
            point.familyLatin = getString(sheet, rowNum, 4);
            point.genusChinese = getString(sheet, rowNum, 5);
            point.genusLatin = getString(sheet, rowNum, 6);
            point.speciesFeatureDesc = getString(sheet, rowNum, 7);
            point.habitatDesc = getString(sheet, rowNum, 8);
            point.protectionLevel = getString(sheet, rowNum, 9);

            point.utilValue = getString(sheet, rowNum, 10);
            point.photoId = getString(sheet, rowNum, 11);
            point.habitatPhotoId = getString(sheet, rowNum, 12);
            points.push(point);
          }
          allData[sheetName] = points;
        });
        resolve(allData); // 返回对象，键为Sheet名，值为对应数组
      } catch (error) {
        reject(error);
      }
    };
    reader.onerror = (error) => reject(error);
    reader.readAsArrayBuffer(file);  // 或者 readAsArrayBuffer(file) 并调整 type 为 'array'
  });
}
function getString(sheet, rowNum, col) {
  const cellAddress = XLSX.utils.encode_cell({ r: rowNum, c: col });
  const cell = sheet[cellAddress];
  if (!cell) return null;
  const val = (cell.v || '').toString().trim();
  return val === '' ? null : val;
}

function getNumber(sheet, rowNum, col) {
  const val = getString(sheet, rowNum, col);
  if (val === null) return null;
  const num = parseFloat(val);
  return isNaN(num) ? null : num;
}

function getInteger(sheet, rowNum, col) {
  const val = getString(sheet, rowNum, col);
  if (val === null) return null;
  const num = parseInt(val, 10);
  return isNaN(num) ? null : num;
}

function getDate(sheet, rowNum, col) {
  const val = getString(sheet, rowNum, col);
  if (val === null || val.trim() === '') return null;

  // 如果Excel日期是数字（序列号），使用 XLSX.SSF.parse_date_code(cell.v) 转换
  const cellAddress = XLSX.utils.encode_cell({ r: rowNum, c: col });
  const cell = sheet[cellAddress];
  if (cell && cell.t === 'n' && cell.w) {  // 如果是日期格式的数字
    return new Date(cell.w);  // cell.w 是格式化字符串
  }
  const date = new Date(val);
  return isNaN(date.getTime()) ? null : date;
}